#include "constants.h";
#include "macros.h";
#include "setup.sqf";
#include "mission.sqf";

if (d_global_debug > 0) then { diag_log Format["Debugging messages activated: %1", d_global_debug]; };

diag_log Format["(%1)[%2]: %3",diag_tickTime,"init.sqf",format["############################# %1 #############################", missionName]];

//configFile>>"CfgWorlds">>worldName>>"centerPosition"
diag_log Format["World Name: %1",worldName];
diag_log Format["World Desc: %1",getText (configFile>>"CfgWorlds">>worldName>> "description")];
diag_log Format["World Mod Name: %1",tolower(getText (configFile>>"CfgWorlds">>worldName>> "worldname"))];
diag_log Format["World Id: %1",getNumber (configFile>>"CfgWorlds">>worldName >> "worldid")];
diag_log Format["World Center: %1",getArray (configFile>>"CfgWorlds">>worldName >> "centerPosition")];
diag_log Format["Mission Version: %1",d_mission_version];

CurrentWorld = toLower(getText (configFile>>"CfgWorlds">>worldName>> "worldname"));
CurrentWorldName = "chernarus";
switch (CurrentWorld) do {
	case "\ibr\lingor\lingor.wrp":
	{
		CurrentWorldName = "lingor";
	};
	case "\ibr\dingor\dingor.wrp":
	{
		CurrentWorldName = "dingor";
	};
	case "cla\clafghan\clafghan.wrp":
	{
		CurrentWorldName = "clafghan";
	};
	case "\ca\takistan\takistan.wrp":
	{
		CurrentWorldName = "takistan";
	};
	case "\ibr\isladuala\isladuala.wrp":
	{
		CurrentWorldName = "isladuala";
	};
	case "hotze\hotze_everon2010\everon2010.wrp":
	{
		CurrentWorldName = "everon2010";
	};
	case "\ibr\panthera2\panthera2.wrp":
	{
		CurrentWorldName = "panthera2";
	};
};

if (!isNil "d_init_started") exitWith {};
d_init_started = true;

enableSaving [false,false];
enableTeamSwitch (!isnil "enemy_commander");

X_INIT = false;X_Server = false; X_Client = false; X_JIP = false;X_SPE = false;X_MP = isMultiplayer;
X_LOADED = false;
X_PLAYER_INIT = false;

#define __waitpl [] spawn {waitUntil {!isNull player};X_INIT = true}
if (isServer) then {
	X_Server = true;
	if (!isDedicated) then {
		X_Client = true;
		X_SPE = true;
		__waitpl;
	} else {
		X_INIT = true;
	};
} else {
	X_Client = true;
	if (isNull player) then {
		X_JIP = true;
		__waitpl;
	} else {
		X_INIT = true;
	};
};

if (d_global_debug > 0) then { 
	diag_log Format["X_INIT   %1",(If (X_INIT) then { "True" } else { "False" })];
	diag_log Format["X_Server %1",(If (X_Server) then { "True" } else { "False" })];
	diag_log Format["X_Client %1",(If (X_Client) then { "True" } else { "False" })];
	diag_log Format["X_JIP    %1",(If (X_JIP) then { "True" } else { "False" })];
	diag_log Format["X_SPE    %1",(If (X_SPE) then { "True" } else { "False" })];
	diag_log Format["X_MP     %1",(If (X_MP) then { "True" } else { "False" })];
};

if (X_Client) then {
	[] spawn {
		waituntil {X_INIT};
		// TODO: Study if it's needed
		// d_phd_invulnerable = true;
		// __pSetVar ["d_p_ev_hd_last", time];
		// __pSetVar ["d_p_ev_hd", player addeventhandler ["HandleDamage", {_this call XfHitEffect}]];
		if (d_global_debug > 0) then { diag_log Format["(%1)[%2]: %3",diag_tickTime,"init.sqf","Starting tasks.sqf"]; };
		execVM "tasks.sqf";
		if (d_global_debug > 0) then { diag_log Format["(%1)[%2]: %3",diag_tickTime,"init.sqf","Ended tasks.sqf"]; };
	};
};

// fix for delayed LHD creation on clients
// I use it also in order to teleport to the LHD_Later
if (X_Client And (!isNil "LHD_Center")) then {
	[] spawn {
		private ["_dirp", "_posp"];
		waituntil {X_INIT};
		if ((player distance LHD_Center) < 200) then {
			_dirp = direction player;
			_posp = [(position player) select 0,(position player) select 1, (position player) select 2];
			if (isNull (nearestobject [player, "Land_LHD_4"])) then {
				player setPos [(markerPos "respawn_west") select 0, (markerPos "respawn_west") select 1, 0];
				waituntil {!isNull (nearestObject [_posp, "Land_LHD_4"])};
			};
			player setPosASL [_posp select 0, _posp select 1, 16];
			player setDir _dirp;
		};
	};
};
if (X_Client) then {
	x_LHD_teleport_position = [0,0,0];
	If (!isNil("LHD_Center")) then {
		[] spawn {
			private ["_posp","_LHDspawnpoint"];
			_LHDspawnpoint = [getPosASL LHD_Center select 0, getPosASL LHD_Center select 1, -0.9];
			waituntil { (X_INIT OR X_SPE) };
			_posp = _LHDspawnpoint;
			waituntil { (!isNull (nearestObject [_LHDspawnpoint, "Land_LHD_2"])) };
			_posp = getPos (nearestObject [_LHDspawnpoint, "Land_LHD_2"]);
			// We now have a position on the deck of the carrier we can teleport to.
			x_LHD_teleport_position = [_posp select 0, _posp select 1, 9.26];
			if (d_global_debug > 0) then { diag_log Format["(%1)[%2]: %3:%4",diag_tickTime,"init.sqf","LHD Teleport Position set to",x_LHD_teleport_position]; };
		};	
	};
};

// We check if the global variable has been initialized. If not, it means we didn't go through the scripts yet.
__cppfln(XReloadVehicle,common\reloadvehicle.sqf);
__cppfln(XLoadVehicleBox,common\loadvehiclebox.sqf);
__cppfln(XCreateWeaponArray,scripts\wpn_array.sqf);
__cppfln(BI_fnc_objectMapper,server\functions\fn_objectMapper.sqf);
__ccppfln(common\functions\commonfunctions.sqf);
__ccppfln(common\functions\netfunctions.sqf);
__ccppfln(common\functions\hash_array.sqf);
__ccppfln(common\functions\reservedvehicle.sqf);
if (d_global_debug > 0) then { diag_log Format["(%1)[%2]: %3 (mission:%4)",diag_tickTime,"init.sqf","Compiled reloadvehicle.sqf, commonfunctions.sqf, netfunctions.sqf",! isnil "d_mission_functions_compiled"]; };

if (d_global_debug > 0) then { diag_log Format["(%1)[%2]: %3",diag_tickTime,"init.sqf",format["Starting i_common.sqf"]]; };
// i_common initializes many global variables which are used by both the client and the server
// for the creation of units, triggers, etc.
// Ex: Base position, Side names, Players, Static positions (like towns)
_common_name = format["islands\%1.common.sqf",CurrentWorldName];
diag_log Format["(%1)[%2]: %3: %4",diag_tickTime,"init.sqf","island file",_common_name];
call compile preprocessfilelinenumbers _common_name;

// switch (CurrentWorld) do {
	// case "\ibr\lingor\lingor.wrp":
	// {
		// #include "islands\lingor.common.sqf";
	// };
	// case "\ibr\dingor\dingor.wrp":
	// {
		// #include "islands\dingor.common.sqf";
	// };
	// case "cla\clafghan\clafghan.wrp":
	// {
		// #include "islands\clafghan.common.sqf";
	// };
	// case "\ca\takistan\takistan.wrp":
	// {
		// #include "islands\takistan.common.sqf";
	// };
	// case "\ibr\isladuala\isladuala.wrp":
	// {
		// #include "islands\isladuala.common.sqf";
	// };
	// case "hotze\hotze_everon2010\everon2010.wrp":
	// {
		// #include "islands\everon2010.common.sqf";
	// };
	// case "\ibr\panthera2\panthera2.wrp":
	// {
		// #include "islands\panthera2.common.sqf";
	// };
	// default
	// {
		// #include "islands\chernarus.common.sqf";
	// };
// };
#include "i_params.sqf";
#include "i_common.sqf";
if (d_global_debug > 0) then { diag_log Format["(%1)[%2]: %3",diag_tickTime,"init.sqf","Ended i_common.sqf"]; };
diag_log Format["(%1)[%2]: %3: %4",diag_tickTime,"init.sqf","Start Time",d_TimeOfDay];
if (isServer) then {skiptime d_TimeOfDay};

if (X_Server) then {
	[] spawn {
			[d_own_side,d_ammobox_weapon_quantity] call XCreateWeaponArray;
			if (d_global_debug > 0) then { diag_log Format["(%1)[%2]: %3",diag_tickTime,"init.sqf","Weapon arrays created.sqf"]; };
		};
};

if (d_global_debug > 0) then { 
	If (!isNil("g_oEventHolder")) then {
		diag_log Format["(%1)[%2]: %3",diag_tickTime,"init.sqf","The Event Holder object is created"];
	} else {
		diag_log Format["(%1)[%2]: %3",diag_tickTime,"init.sqf","No Event Holder found!"];
	};
	If (!isNil("JIP_HINV")) then {
		diag_log Format["(%1)[%2]: %3",diag_tickTime,"init.sqf","The Shared Variables Holder object is created"];
	} else {
		diag_log Format["(%1)[%2]: %3",diag_tickTime,"init.sqf","No Shared Variables Holder found!"];
	};
};

X_LOADED = true;

if (d_global_debug > 0) then { diag_log Format["(%1)[%2]: %3",diag_tickTime,"init.sqf","Adding common XNetEvents"]; };
[0, "rep_ar", {_this setDamage 0;_this setFuel 1}] call XNetAddEvent;
[0, "setcapt", {(_this select 0) setCaptive (_this select 1)}] call XNetAddEvent;
[0, "setweather", {_delay = _this select 0; _delay setRain (_this select 1); _delay setOvercast (_this select 2);}] call XNetAddEvent;
[0, "d_say", {(_this select 0) say3D (_this select 1)}] call XNetAddEvent;
// Execute the given code on all systems
[0, "d_all_exec", {diag_log format["[%1] %2","d_all_exec",_this]; _this spawn compile (_this select 0)}] call XNetAddEvent;
// registers a new mission object on all systems
[0, "d_all_mobject", {waituntil{!(isNil "d_mission_functions_compiled")};_this call XfMissionRegisterObject;}] call XNetAddEvent;
// create/update/delete a mission marker on all systems
[0, "d_all_mmarker", {_this call XfMissionUpdateMarker;}] call XNetAddEvent;
// Executes an action triggered by a mission object on all systems
[0, "d_all_maction", {_this call XfMissionExecuteObjectAction;}] call XNetAddEvent;
// Creates/Updates a mission task on all systems
[0, "d_all_mtask", {[_this,false] call XfMissionUpdateTask;}] call XNetAddEvent;
// Cleans all mission elements
[0, "d_all_mclean", {_this call XfMissionCleanEvent;}] call XNetAddEvent;
// TODO: Study how to add it back
//[0, "d_flav", {[_this] spawn x_flares}] call XNetAddEvent;
// TODO: No idea yet what this does... not needed in my opinion.
[0, "d_del_ruin", {_ruin = nearestObject [_this, "Ruins"];if (!isNull _ruin) then {deleteVehicle _ruin}}] call XNetAddEvent;
// Launches the mission with the ID and parameters given
[0, "d_all_mlaunch", {_this execVM "missions\launch_mission.sqf";}] call XNetAddEvent; // different handling
// Executes a mission function on all systems.
[0, "d_all_mexecute", {_fnct = _this select 0; _params = _this select 1; call compile Format["%1 spawn %2",_params, _fnct];}] call XNetAddEvent; // different handling
// Switches move for all players
[0, "d_nswm", {(_this select 0) switchmove (_this select 1)}] call XNetAddEvent;

if (isServer) then {
	if (d_global_debug > 0) then { diag_log Format["(%1)[%2]: %3",diag_tickTime,"init.sqf","Adding Server XNetEvents"]; };
	[1, "d_dam", {_this call XDamHandler}] call XNetAddEvent; // different handling
	// Creates a box dropped from a vehicle (MHQ or Chopper)
	[1, "d_m_box", {_this spawn XCreateDroppedBox}] call XNetAddEvent;
	// Creates a box dropped through call AirDrop
	[1, "d_air_box", {_this spawn XCreateDroppedBox}] call XNetAddEvent;
	[1, "d_p_group", {if (!(_this in d_player_groups)) then {d_player_groups set [count d_player_groups, _this]}}] call XNetAddEvent;
	// Calls the old style airtaxi without the ability to choose a location (only to return to base)
	[1, "d_air_taxi", {_this execVM "server\airtaxiserver.sqf"}] call XNetAddEvent;
	// Removes a box which was dropped from a vehicle
	[1, "d_r_box", {_this spawn XRemABox}] call XNetAddEvent;
	[1, "d_pas", {(_this select 0) addScore (_this select 1)}] call XNetAddEvent;
	[1, "mr1_l_c", {if (!isNull _this) then {[_this, 1] spawn x_checktransport}}] call XNetAddEvent;
	[1, "mr2_l_c", {if (!isNull _this) then {[_this, 2] spawn x_checktransport}}] call XNetAddEvent;	
	[1, "d_p_varn", {_this spawn XGetPlayerArray}] call XNetAddEvent;
	[1, "d_p_o_a", {d_placed_objs_store setVariable [_this select 0, _this select 1];((_this select 1) select 0) setVariable ["d_owner", _this select 0];((_this select 1) select 0) addEventHandler ["killed",{_this call XfPlacedObjKilled}]}] call XNetAddEvent;
	[1, "d_p_o_r", {d_placed_objs_store setVariable [_this select 0, nil]}] call XNetAddEvent;
	// Creates the drop vehicle and gets it to the destination
	[1, "x_dr_t", {_this execVM "server\createdrop.sqf"}] call XNetAddEvent;
	// Locks/Unlocks a vehicle. This is accessible to the admin only.
	[1, "l_v", {if (alive(_this select 0)) then {(_this select 0) lock (_this select 1)}}] call XNetAddEvent;
	// Deploying the MHQ
	_deploy_mhq = {
		_count = count (configFile >> "CfgVehicles" >> (typeof (_this select 0)) >> "Turrets");
		// diag_log Format["(%1)[%2]: %3: %4 (%5)",diag_tickTime,"init.sqf","DeployEvent", _this, _count];
		(_this select 0) lock (_this select 1);
		for [{_i = 0},{_i < _count},{_i = _i + 1}] do {
			(_this select 0) lockTurret [[_i],(_this select 1)];
		};
		d_allunits_add set [count d_allunits_add, (_this select 0) getVariable "D_MHQ_Camo"];
	};
	// [1, "d_mhqdepl", {(_this select 0) lock (_this select 1); (_this select 0) lock (_this select 1); d_allunits_add set [count d_allunits_add, (_this select 0) getVariable "D_MHQ_Camo"]}] call XNetAddEvent;
	[1, "d_mhqdepl",_deploy_mhq] call XNetAddEvent;
	[1, "d_g_p_inf", {_this spawn XGetAdminArray}] call XNetAddEvent;
	// Triggers the creation of reinforcement units on a location: Argument is in the form [[x,y,z],300 (=radius),"PARA"(=type:ROAD,PARA),1(=power:1-3)]
	[1, "d_c_e_reinf", { _this execVM "server\sendreinforcement.sqf" }] call XNetAddEvent;
	// Triggers the creation of reinforcement units on a location: Argument is in the form [[x,y,z],300 (=radius),"PARA"(=type:ROAD,PARA),1(=power:1-3)]
	[1, "d_s_mreinf", { _this execVM "missions\mission_reinforcement.sqf" }] call XNetAddEvent;
	// This is the creation of the AirTaxi new style, with the ability to chose a destination and select waypoints
	[1, "d_air_taxi2", { _this execVM "server\airtaxiserver2.sqf" }] call XNetAddEvent;
	// This will run the called code on the server only with the first array of the element being the code
	[1, "d_s_exec", {_this spawn compile (_this select 0)}] call XNetAddEvent;
	// Executes a mission function on the server.
	[1, "d_s_mexecute", {_fnct = {}; call compile Format["_fnct = %1;",(_this select 0)]; _params = _this select 1; _params spawn _fnct;}] call XNetAddEvent; // different handling
	// This is the creation of the AirTaxi new style, with the ability to chose a destination and select waypoints
	[1, "d_halo_request", { _this execVM "server\halogroup.sqf" }] call XNetAddEvent;
};

switch (CurrentWorld) do {
	case "\ibr\lingor\lingor.wrp":
	{
		#include "islands\lingor.server.sqf";
	};
	case "\ibr\dingor\dingor.wrp":
	{
		#include "islands\dingor.server.sqf";
	};
	case "cla\clafghan\clafghan.wrp":
	{
		#include "islands\clafghan.server.sqf";
	};
	case "\ca\takistan\takistan.wrp":
	{
		#include "islands\takistan.server.sqf";
	};
	case "\ibr\isladuala\isladuala.wrp":
	{
		#include "islands\isladuala.server.sqf";
	};
	case "hotze\hotze_everon2010\everon2010.wrp":
	{
		#include "islands\everon2010.server.sqf";
	};
	case "\ibr\panthera2\panthera2.wrp":
	{
		#include "islands\panthera2.server.sqf";
	};
	default
	{
		#include "islands\chernarus.server.sqf";
	};
};

#include "i_server.sqf"
#include "i_client.sqf"

if (d_global_debug > 0) then { diag_log Format["(%1)[%2]: %3",diag_tickTime,"init.sqf","Ending i_server and i_client.sqf"]; };

If (d_revive_script == "NORRN") then {
	d_still_in_intro = false;
	if (d_global_debug > 0) then { diag_log Format["(%1)[%2]: %3",diag_tickTime,"init.sqf","Using NORRN REVIVE"]; };
	execVM "r_init.sqf";
};

// Initializing the R3F Artillery and Logistics module.
execVM "R3F_ARTY_AND_LOG\init.sqf";
R3F_Param_Garbage_Auto = True;
call compile preprocessFile "R3F_ACV\Scripts\ACV_init.sqf";

if (X_SPE) then {d_date_str = date};

if (isServer) then {
	// The following statements are needed in order to be able to spawn units of all sides and have them be enemy to the right sides, otherwise it turns into Carebear land :)
	createCenter east;
	createCenter west;
	createCenter Resistance;
	createCenter civilian;
	createCenter sideLogic;
	
	west setFriend [east, 0];
	east setFriend [west, 0];
	west setFriend [civilian, 1];
	east setFriend [civilian, 1];
	civilian setFriend [west, 1];
	civilian setFriend [east, 1];
	civilian setFriend [Resistance, 1];

	Resistance setFriend [civilian, 1];
	if (d_own_side == "WEST") then {
		if (d_resistance_is_friendly > 0) then {
			west setFriend [Resistance, 1];
			east setFriend [Resistance, 0];
			Resistance setFriend [west, 1];
			Resistance setFriend [east, 0];
		} else {
			west setFriend [Resistance, 0];
			east setFriend [Resistance, 1];
			Resistance setFriend [west, 0];
			Resistance setFriend [east, 1];
		};
	} else {
		if (d_resistance_is_friendly > 0) then {
			west setFriend [Resistance, 0];
			east setFriend [Resistance, 1];
			Resistance setFriend [west, 0];
			Resistance setFriend [east, 1];
		} else {
			west setFriend [Resistance, 1];
			east setFriend [Resistance, 0];
			Resistance setFriend [west, 1];
			Resistance setFriend [east, 0];
		};
	};
	
	d_allunits_add = [];
	d_check_boxes = [];
	if (d_global_debug > 0) then { diag_log Format["(%1)[%2]: %3",diag_tickTime,"init.sqf","Start setting XNetJIP variables"]; };
	["target_clear",false] call XNetSetJIP;
	["the_end",false] call XNetSetJIP;
	["mr1_in_air",false] call XNetSetJIP;
	["mr2_in_air",false] call XNetSetJIP;
	["d_jet_s_reb",false] call XNetSetJIP;
	["d_chopper_s_reb",false] call XNetSetJIP;
	// The number of ammoboxes created in the game.
	["ammo_boxes",0] call XNetSetJIP;
	// The array containing all ammoboxes which were dropped from a vehicle (like MHQ or chopper)
	["d_ammo_boxes",[]] call XNetSetJIP;
	// A drop vehicle is available (none in flight)
	["para_available",true] call XNetSetJIP;
	["d_dam",[]] call XNetSetJIP;
	["d_weapon_array_west",[]] call XNetSetJIP;
	["d_weapon_array_east",[]] call XNetSetJIP;
	// The maximum amount of drop vehicles available, once they got all killed.. no air drop anymore.
	["available_drop_vehicles",d_available_drop_vehicles] call XNetSetJIP;
	// Indicates whether the current mission is completed or not (this will stop reinforcement from coming)
	["current_mission_id",0] call XNetSetJIP; 
	// This is where reinforcement will be sent and the radius is used for patrols. Position, Radius, MarkerName
	["current_mission_position",[[0,0,0],0,""]] call XNetSetJIP;
	// Indicates whether the current mission is completed or not (this will stop reinforcement from coming)
	["current_mission_completed",false] call XNetSetJIP; 
	// The list of tasks currently registered to the mission and their current state
	// The form of a task is: ["uniquename", "title", "description","waypoint desc",[waypoint pos], "status"]
	["current_mission_tasks",[]] call XNetSetJIP; 
	// Contains a list of all markers for the currently loaded mission. Those are markers from the briefing.
	// A marker item has all info needed to call XCreateMarkerLocal (allows synch for JIP)
	["current_mission_markers",[]] call XNetSetJIP;
	// This list contains all units specific to a mission (hostage, special target, special vehicle, etc)
	// It is used at the end of the mission to clean it.
	["current_mission_units",[]] call XNetSetJIP;
	// This list contains all the "triggers" for the current mission. They all need to have a status different than 0 for the mission to complete.
	// A status of 1 is complete, -1 is failed.
	// Ex: ["objective_name",0,"Objective Description", "Objective 1 success message", "Objective 1 Fail message"]
	["current_mission_objectives",[]] call XNetSetJIP;
	// Used to know if the AirTaxi is available
	["airtaxi_available",[]] call XNetSetJIP;
	// This value is used to cancel all reinforcement currently under way.
	["reinforcement_canceled",False] call XNetSetJIP;
	// This variable will store all missions available which will be displayed in the list of missions.
	["available_missions",[]] call XNetSetJIP;
	
	if (d_global_debug > 0) then { 
		diag_log "";
		diag_log Format["JIPH mr1_in_air %1",(["mr1_in_air","empty"] call XNetGetJIP)];
		diag_log Format["JIPH mr2_in_air %1",(["mr2_in_air","empty"] call XNetGetJIP)];
		diag_log Format["JIPH ammo_boxes %1",(["ammo_boxes","empty"] call XNetGetJIP)];
		diag_log Format["JIPH d_ammo_boxes %1",(["d_ammo_boxes","empty"] call XNetGetJIP)];
		diag_log Format["JIPH para_available %1",(["para_available","empty"] call XNetGetJIP)];
		diag_log Format["JIPH current_target_position %1",(["current_target_position","empty"] call XNetGetJIP)];
		diag_log Format["JIPH current_mission_completed %1",(["current_mission_completed","empty"] call XNetGetJIP)];
		diag_log Format["JIPH available_drop_vehicles %1",(["available_drop_vehicles","empty"] call XNetGetJIP)];
		diag_log Format["JIPH current_mission_markers %1",(["current_mission_markers","empty"] call XNetGetJIP)];
		diag_log Format["JIPH current_mission_units %1",(["current_mission_units","empty"] call XNetGetJIP)];
		diag_log Format["JIPH current_mission_objectives %1",(["current_mission_objectives","empty"] call XNetGetJIP)];
		diag_log Format["JIPH airtaxi_available %1",(["airtaxi_available","empty"] call XNetGetJIP)];
		diag_log "";
		//diag_log Format["ObjPos1: %1",getPos ObjPos1];
		// diag_log Format["ObjPos2: %1",getPos ObjPos2];
	};
	
	
	// This value is set back to false when all paras from the createpara.sqf script are dead.
	d_create_new_paras = false;
	// The list of groups of paradropped units present on the mission position.
	d_c_attacking_grps = [];
	
	X_DropZone = createVehicle ["HeliHEmpty", [0, 0, 0], [], 0, "NONE"];
	["X_DropZone",X_DropZone] call XNetSetJIP;
	if (d_global_debug > 0) then { 
		diag_log Format["(%1)[%2]: %3",diag_tickTime,"init.sqf",Format["Drop zone created at %1",getPos X_DropZone]];
		diag_log Format["JIPH X_DropZone %1",(["X_DropZone","empty"] call XNetGetJIP)];
	};
	
	__ccppfln(server\initx.sqf);
	if (d_global_debug > 0) then { diag_log Format["(%1)[%2]: %3",diag_tickTime,"init.sqf","Done call compiling initx.sqf"]; };

	d_check_trigger = objNull;
	d_create_new_paras = false;
	d_first_time_after_start = true;
	
	if (d_global_debug > 0) then { diag_log Format["(%1)[%2]: %3",diag_tickTime,"init.sqf","Start execution of helirespawn2.sqf"]; };
	
	switch (CurrentWorld) do {
		case "\ibr\lingor\lingor.wrp":
		{
			#include "islands\lingor.vehicles.sqf";
		};
		case "\ibr\dingor\dingor.wrp":
		{
			#include "islands\dingor.vehicles.sqf";
		};
		case "cla\clafghan\clafghan.wrp":
		{
			#include "islands\clafghan.vehicles.sqf";
		};
		case "\ca\takistan\takistan.wrp":
		{
			#include "islands\takistan.vehicles.sqf";
		};
		case "\ibr\isladuala\isladuala.wrp":
		{
			#include "islands\isladuala.vehicles.sqf";
		};
		case "hotze\hotze_everon2010\everon2010.wrp":
		{
			#include "islands\everon2010.vehicles.sqf";
		};
		case "\ibr\panthera2\panthera2.wrp":
		{
			#include "islands\panthera2.vehicles.sqf";
		};
		default
		{
			#include "islands\chernarus.vehicles.sqf";
		};
	};

	// editor varname, unique number, true = respawn only when the chopper is completely destroyed, false = respawn after some time when no crew is in or chopper is destroyed
	//100-109 = Chopper MHQ, 300-399 = Chopper, 400-499 = Plane
	if (isnil "x_aerial_init") then {
		x_aerial_init = [
			[ch1,301,true],[ch2,302,true],[ch3,303,true],[ch4,304,true],[ch5,305,true],[ch6,306,true],
			[ap1,401,false,300],[ap2,402,false,300],[ap3,403,false,300]
		];
	};
	x_aerial_init execVM "server\helirespawn2.sqf";
	
	if (d_global_debug > 0) then { diag_log Format["(%1)[%2]: %3",diag_tickTime,"init.sqf","Start execution of vrespawn2.sqf"]; };
	// editor varname, unique number, with or without camo at base
	// You need to create the vehicles in the mission editor and give them specific names that you'll use here.
	// Then you add them to the array with a numeric value like shown below and they'll get special treatments.
	//0-9 = MHQ, 10-19 = Medic vehicles, 20-29 = Fuel, Repair, Reammo trucks, 30-39 = Engineer Salvage trucks, 40-49 = Transport trucks
	//True/False : create camo over the vehicle at the base.
	if (isnil "x_vehicle_init") then {
		x_vehicle_init = 	[
			[xvec1,0,False],[xvec2,1,False],[xmedvec,10,False],
			[xvec3,20,True],[xvec4,21,True],[xvec5,22,True], [xvec6,30,True],[xvec7,40,True], [xvec8,41,True],
			[xarm1,42,True], [xarm2,43,True], [xarm3,44,True],
			[xcar1,46,False], [xcar2,47,False], [xcar3,48,False], [xcar4,49,False], [xcar5,50,False], [xcar6,51,False],
			[xmot1,52,False], [xmot2,53,False], [xmot3,54,False], [xmot4,55,False],
			[xstat1,56,False], [xstat2,57,False], [xstat3,58,False], [xstat4,59,False],
			[xboat1,60,False], [xboat2,61,False], [xboat3,62,False], [xboat4,63,False]
		];
	};
	x_vehicle_init execVM "server\vrespawn2.sqf";

	execVM "server\setupserver.sqf";

	// Here is how you'll start sending air vehicles to a target destination.
	//["current_target_position",d_base_array select 0] call XNetSetJIP; // This is to give a direction for the random spawn of Air vehicles.

	d_player_store = "HeliHEmpty" createVehicleLocal [0, 0, 0];
	d_placed_objs_store = "HeliHEmpty" createVehicleLocal [0, 0, 0];
	d_player_groups = [];

	__cppfln(XfServerOPC,server\serverOPC.sqf);
	__cppfln(XfServerOPD,server\serverOPD.sqf);
	onPlayerConnected "xhandle = [_name,_uid] spawn XfServerOPC;";
	onPlayerDisconnected "xhandle = [_name,_uid] spawn XfServerOPD; [_name, _id, _uid] spawn XfMissionPlayerDisconnected;";
	onTeamSwitch {[_from, _to] execVM "AEG\Scripts\AEG_team.sqf";};
	
	__ccppfln(scripts\building_position.sqf);
	
	KRON_UPS_OwnSideOverride = d_own_side;
	execVM "scripts\UPSMONinit.sqf";
	execVM "missions\mission_init.sqf";
};
if (!isnil "TYR_FNCT_Compiled") then {
	call compile PreProcessFileLineNumbers "missions\TYR_FNCT_mission.sqf";
};

// Spawn of the LHD Carrier. Place an invisible Helipad where the Carrier should be centered. The direction of the Helipad is used for the carrier too.
if (!isNil("LHD_Center")) then {
	execVM "common\createcarrier.sqf";
};

if (X_Client) then {
	sleep 0.1;
	execVM "R3F_DEBUG\scripts\functions_R3F_Debug.sqf";
};

_marker_pos = markerPos "marker_zone";
if ((_marker_pos distance [0,0,0]) > 1) then {
	_eligible_towns = [d_map_locations, [XF_MAP_LOCATION_TYPE,"IN",[XF_MAP_LOCATION_TYPE_TOWN,XF_MAP_LOCATION_TYPE_VILLAGE]]] call XfTableFilter;
	diag_log Format["(%1)[%2]: %3 (%4)",diag_tickTime,"init.sqf","Eligible Towns", (count _eligible_towns)];
	// [_eligible_towns, "   "] call XfArrayDump;
	_towns = [];
	_marker_size = markerSize "marker_zone";
	_marker_dir = markerDir "marker_zone";
	_marker_text= markerText "marker_zone";
	_marker_rectangle = ((markerShape "marker_zone") == "RECTANGLE");
	{
		_town = _x;
		_valid = false;
		_valid = [(_town select XF_MAP_LOCATION_CENTER), _marker_pos, ((_marker_size select 0) * 2), ((_marker_size select 1) * 2), _marker_dir] call XfPointInSquare;
		if (_valid) then {_towns set [ count _towns, _town ]; };
	} foreach _eligible_towns;
	diag_log Format["(%1)[%2]: %3: %4  %5: %6",diag_tickTime,"init.sqf","Zone",[0,_marker_pos,_marker_text,Format["Sec%1",_marker_text],((_marker_size select 0) * 2), ((_marker_size select 1) * 2), _marker_dir,_marker_rectangle],"Towns",_towns];
	_names = [];
	{
		_names set [count _names, _x select XF_MAP_LOCATION_DISPLAYNAME];
	} foreach _towns;
	sleep 3;
	["d_msg",[Format["Found Towns: %1", _names],"all",objNull,"hq"]] call XNetCallEvent;
};
